import { PureComponent } from "react"

export default class Form extends PureComponent {
  constructor() {
    super()
    this.state = {
      username: "",
      password: "",
      hobbies: [
        // 爱好
        { name: "唱", checked: false },
        { name: "跳", checked: false },
        { name: "rap", checked: false }
      ],
      foods: [],
      isAgree: false
    }
  }

  onSubmit(e) {
    // 不阻止的话就会刷新网页了
    e.preventDefault()
    const { username, password, hobbies, foods, isAgree } = this.state
    console.log(username, "获取用户名")
    console.log(password, "获取密码")
    console.log(isAgree, "获取用户是否同意")
    const hobbiesParams = hobbies
      .filter((item) => item.checked)
      .map((item) => item.name)
    console.log(hobbiesParams, "获取爱好多选框传给服务端")
    console.log(foods, "获取食物下拉多选")
  }

  selectChange(e) {
    const foods = [...this.state.foods]
    foods.push(e.target.value)
    this.setState({
      foods
    })
  }

  checkboxChange(e, index) {
    const hobbies = [...this.state.hobbies]
    hobbies[index]["checked"] = e.target.checked
    this.setState({
      hobbies
    })
  }

  inputChange(e) {
    const keyName = e.target.name
    this.setState({
      [keyName]: e.target.value
    })
  }

  radioChange(e) {
    const keyName = e.target.name
    this.setState({
      [keyName]: e.target.checked
    })
  }

  render() {
    const { username, password, hobbies, foods, isAgree } = this.state
    return (
      <div>
        {/*非受控表单*/}
        <form onSubmit={(e) => this.onSubmit(e)}>
          <div className="borderSplit">
            <label>用户名:</label>
            <input
              type="text"
              name="username"
              value={username}
              onChange={(e) => this.inputChange(e)}
            />
          </div>
          <div className="borderSplit">
            <label>密码:</label>
            <input
              type="password"
              name="password"
              value={password}
              onChange={(e) => this.inputChange(e)}
            />
          </div>
          {hobbies.map((item, index) => (
            <span key={index}>
              <input type="checkbox"
                onChange={(e) => this.checkboxChange(e, index)}
              />
              {item.name}
            </span>
          ))}
          <br />
          <div className="borderSplit">
            <select
              multiple={true}
              value={foods}
              onChange={(e) => this.selectChange(e)}
            >
              <option>苹果</option>
              <option>香蕉</option>
            </select>
          </div>

          <div>
            <input
              type="radio"
              name="isAgree"
              value={isAgree}
              onChange={(e) => this.radioChange(e)}
            />
            是否同意用户协议
          </div>
          <button type="submit">提交</button>
        </form>
      </div>
    )
  }
}
